package controller

import (
	"context"
	"gf2DemoServer/api/v1"
	"github.com/gogf/gf/v2/errors/gcode"
	"github.com/gogf/gf/v2/errors/gerror"
	"github.com/gogf/gf/v2/os/gfile"
	"github.com/gogf/gf/v2/os/gtime"
	"github.com/gogf/gf/v2/text/gstr"
)

var (
	Upload = cUpload{}
)

type cUpload struct{}

// File 上传文件
func (c *cUpload) File(ctx context.Context, req *v1.UploadReq) (res *v1.UploadRes, err error) {
	if req.File == nil {
		return nil, gerror.NewCode(gcode.CodeMissingParameter, "请选择需要上传的文件")
	}
	dirPath := "resource/public/upload" + gtime.Now().Format("/Ym/")
	if !gfile.IsDir(dirPath) {
		err = gfile.Mkdir(dirPath)
		if err != nil {
			return nil, gerror.NewCode(gcode.CodeOperationFailed, "上传目录创建失败")
		}
	}
	filename, err := req.File.Save(dirPath, true)
	if err != nil {
		return nil, gerror.NewCode(gcode.CodeOperationFailed, "上传失败")
	}
	path := gstr.SubStr(dirPath, 15) + filename
	res = &v1.UploadRes{
		Name: filename,
		Path: path,
		Url:  "http://localhost:8199" + path,
	}
	return
}
